package com.icehand.payment.api.v1.controller;

import com.icehand.common.model.BaseUser;
import com.icehand.common.result.BizResult;
import com.icehand.payment.api.v1.service.PayChannelServiceV1;
import com.icehand.payment.api.v1.service.PayServiceV1;
import com.icehand.payment.model.PayRequest;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author icehand
 */
@RestController
@RequestMapping("/api/v1")
public class PayControllerV1 {
    private final PayServiceV1 payServiceV1;
    private final PayChannelServiceV1 payChannelServiceV1;

    @Autowired
    public PayControllerV1(PayServiceV1 payServiceV1, PayChannelServiceV1 payChannelServiceV1) {
        this.payServiceV1 = payServiceV1;
        this.payChannelServiceV1 = payChannelServiceV1;
    }

    /**
     * 注意：因为依赖中引入jackson-dataformat-xml，返回的数据会优先是xml格式的，需要指定返回的数据类型
     */
    @ApiOperation(value = "根据AppId获取支付渠道信息")
    @RequestMapping(value = "/channels",produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public BizResult payChannels(@RequestParam("appId") Integer appId){
        return payChannelServiceV1.payChannels(appId);
    }

    @ApiOperation(value = "生成支付信息")
    @RequestMapping(value = "/pay",produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public BizResult pay(@RequestBody PayRequest payRequest, @RequestAttribute("user")BaseUser user){
        return payServiceV1.pay(payRequest,user);
    }

    @ApiOperation(value = "支付回调信息")
    @RequestMapping("/notify/{appId}/{channelId}")
    public void pay(@PathVariable("channelId")Integer channelId, @PathVariable("appId") Integer appId,
                                   HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.getWriter().write(payServiceV1.payNotify(channelId,appId,request));
    }

    @ApiOperation(value = "退款")
    @RequestMapping("/refund")
    public BizResult refund(){
        return null;
    }
}
